const util = require('../../utils/util');
let app = getApp();
Component({
  properties: {
    fromUser: String,
    curModule: String,
  },
  data: {
    url: '',
    openid: '',
    isShow: false,
    showmask: false,
  },
  created() {
    if (!wx.canIUse('web-view')) {
      wx.showModal({
        title: '提示',
        content: '您的微信版本过低，无法打开本页面，请升级微信至最新版。',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.navigateBack({
              delta: 1,
            });
          }
        },
      });
      return;
    }
  },

  ready() {
    // 兼容商城
    if (this.data.curModule === 'ws_micro_shop') {
      let userinfo = wx.getStorageSync('user_info');
      if (userinfo) {
        if (Number(userinfo.info) === 0) {
          this.setData({
            isShow: false,
          });
        }
        this.getUrl(userinfo);
      } else {
        app.ws_micro_shoplogin().then(res => {
          userinfo = wx.getStorageSync('user_info');
          if (Number(userinfo.info) === 0) {
            this.setData({
              isShow: true,
            });
          }
          this.getUrl(userinfo);
        });
      }
      return;
    }
    util._authUserInfo().then(res => {
      if (res.nickName && res.avatarUrl) {
        this.getUrl(res);
        wx.setStorageSync('needAuthLoginOnPageLoad', false);
      } 
    }).catch(() => {
      this.setData({
        isShow: true,
      });
    });
  },
  methods: {
    // 登陆授权
    updateUsers(e) {
      if (e && e.detail && e.detail.userInfo) {
        const {
          nickname = '', avatar = '',
        } = e.detail.userInfo;
        let user_info = {
          nickname,
          avatarUrl: avatar,
        };
        this.getUrl(user_info);
      } else {
        if (!this.data.fromUser) {
          wx.navigateBack({
            delta: 1,
          });
        } else {
          this.getUrl();
        }
      }
    },

    // 获取活动信息
    getUrl(userinfo) {
      app.util.request({
        url: 'entry//index',
        data: {
          m: 'cm_friend_help',
          op: 'getActivity',
        },
        success: res => {
          let baseUrl = res.data.data;
          let openid = wx.getStorageSync('OPENID') || wx.getStorageSync('userInfo').openid;
          if (userinfo) {
            let nickname = encodeURIComponent(userinfo.nickName || userinfo.nickname);
            let avatar_url = encodeURIComponent(userinfo.avatarUrl || userinfo.avatar_url);
            this.setData({
              url: `${baseUrl}&openid=${openid}&nickname=${nickname}&avatar=${avatar_url}&from_user=${this.data.fromUser}`,
            });
          } else {
            this.setData({
              url: `${baseUrl}&openid=${openid}&from_user=${this.data.fromUser}`,
            });
          }
          this.setData({ icon: res.data.icon || '', save_button: res.data.save_button || '' });
          let message = {
            openid,
            imageUrl: res.data.imgUrl,
            title: res.data.share_title,
          };
          this.triggerEvent('ShareMessage', message);
        },
        fail: () => {
          wx.showModal({
            content: '活动未开启',
            showCancel: false,
            confirmText: '确认',
            success: res => {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1,
                });
              } 
            },
          });
        },
      });
    },

    // 生成海报
    getPost() {
      let that = this;
      let openid = wx.getStorageSync('OPENID') || wx.getStorageSync('userInfo').openid;
      wx.showLoading({
        title: '海报生成中....',
        mask: true,
      });
      app.util.request({
        url: 'entry//index',
        data: {
          m: 'cm_friend_help',
          op: 'getPoster',
          openid: openid,
        },
        success: res => {
          wx.hideLoading();
          that.setData({
            posterImg: res.data.data.img,
          },()=>{
            that.changeMask();
          });
        },
        fail: () => {
          wx.showToast({
            title: '生成海报失败！',
            icon: 'none',
            duration: 1500,
            mask: true,
          });
        },
      });
    },

    changeMask() {
      this.setData({
        showmask: !this.data.showmask,
      });
    },

    // 保存海报
    savePoster(e) {
      if (!wx.saveImageToPhotosAlbum) {
        wx.showModal({
          title: '提示',
          content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
          showCancel: false,
        });
        return;
      }
      wx.getSetting({
        success: (res) => {
          if (typeof res.authSetting['scope.writePhotosAlbum'] === 'undefined') {
            this.downloadPoster();
          } else if (res.authSetting['scope.writePhotosAlbum'] === false) {
            this.setData({
              openSetting: true,
            });
          } else {
            this.downloadPoster(e);
          }
        },
      });
    },

    downloadPoster(e) {
      let that = this;
      wx.showLoading({
        title: '正在下载图片',
        mask: true,
      });
      wx.downloadFile({
        url: this.data.posterImg,
        success: (file) => {
          wx.showLoading({
            title: '正在保存图片',
            mask: true,
          });
          wx.saveImageToPhotosAlbum({
            filePath: file.tempFilePath,
            success: (res) => {
              wx.showToast({
                title: '图片保存成功',
                icon: 'success',
                duration: 1500,
                mask: true,
              });
              that.changeMask();
            },
            fail: (res) => {
              wx.showToast({
                title: '图片保存失败',
                icon: 'none',
                duration: 1500,
                mask: true,
              });
              that.changeMask();
            },
            complete: (res) => {
              wx.hideLoading();
            },
          });
        },
        fail: (e) => {
          wx.showToast({
            title: e.errMsg + ';' + this.data.poster,
            icon: 'none',
            duration: 1500,
            mask: true,
          });
          that.changeMask();
        },
        complete: (e) => {
          wx.hideLoading();
        },
      });
    },
  },
});
